import { useRequest } from '@umijs/hooks';
import {
  Button, Card,DatePicker,
  Form,
  Select,
  Input,
  Layout,
  Menu,
  message,
  Popconfirm,
  Radio,
  Table,
  Tag,
  Tree,
  TreeSelect,
  Upload
} from 'antd';
import { FileExcelOutlined,PlusOutlined} from '@ant-design/icons'
import { Store } from 'rc-field-form/lib/interface';
import React, {useEffect,useState} from 'react';
import { useDispatch, useSelector } from 'react-redux'
import {getOriginString, getSecretString} from '../../../utils/encrypt';
import { fetchRequest } from '../../../utils/Request';
import { url } from '../../../utils/url';
import XLSX from 'xlsx';
import {useSingleState} from "nice-hooks";
import {string} from "prop-types";
import moment from 'moment'
// import actionTypes from '../actionTypes'
import cookie from 'react-cookies';

interface ValidateState {
  state: "" | "success" | "warning" | "error" | "validating" | undefined,
  help: string | undefined,

}
export default function RecordInStudentCard(props: any) {
  const [validatePhoto, setvalidatePhoto] = useState<ValidateState>({ state: undefined, help: undefined })
  const { Header, Content, Footer } = Layout;
  const [excelTableData,setExcelTableData] = useState<any[]>([]);
  const [errorData,setErrorData] = useState<any[]>([]);
  const [batchAddList, setBatchAddList] = useState<any[]>([]);
  const [excelFlag,setExcelFlag] = useState<boolean>(false);
  const [state,setState]=useSingleState({fileStoreName:""})
  const [cardType,setCardType] = useState<number>(1);


  const errorcolumns=[{title: "错误说明", dataIndex: 'errorTitle', key: 'errorTitle'}]
  const columns = [
    {title: "白卡号", dataIndex: 'whiteCardCode', key: 'whiteCardCode',render:(text:string)=>text ===""? <Tag color={'#f50206'}>白卡号未填</Tag>:text },
    {title: "IMEI", dataIndex: 'imeiCode', key: 'imeiCode',render:(text:string)=>text ===""? <Tag color={'#f50206'}>IMEI号未填</Tag>:text }
  ];

  const { Option } = Select;

  function handleExcelFile(e:any) {
    if(e.target.files[0]===null||e.target.files[0]===undefined){
      return false;
    }
    let f = e.target.files[0];
    let reader = new FileReader();  // 使用 FileReader 读取数据
    reader.onload = function(e) {  // 数据读取完成后的回调函数
      try{
        // @ts-ignore
        let workbook = XLSX.read(e.target.result, {type: 'binary'})
        let firstSheetName = workbook.SheetNames[0];  // 获取第一个 sheet 的名字
        let worksheet = workbook.Sheets[firstSheetName];  // 获取第一个 sheet 的内容
        let res = XLSX.utils.sheet_to_json(worksheet);  // 使用 utils 里的方法转换内容为便于使用的数组
        console.log('res',res)
        const list:any[]=[];
        const addList:any[]=[];
        res.map((item:any) => {
        list.push({
            rowNum:item.__rowNum__,
            whiteCardCode: (item.白卡号===""|| item.白卡号===undefined)?"":item.白卡号.trim(),
            imeiCode:  (item.IMEI===""|| item.IMEI===undefined)?"":item.IMEI.trim()
          })

        addList.push({
            whiteCardCode: (item.白卡号===""|| item.白卡号===undefined)?"":item.白卡号.trim(),
            imeiCode:  (item.IMEI===""|| item.IMEI===undefined)?"":item.IMEI.trim()
          })
        });
        // console.log("list数据",list);
        setExcelTableData(list);
        excelDataCheck(addList);
      }
      catch (e) {
        console.log(e);
        message.error("数据异常！");
      }
    };
    reader.readAsBinaryString(f);  // 读取数据
  }

  //验证excel正确性
  function excelDataCheck(data:any) {
    let falseFlag = true;
    let repeatError="";
    for(let i = 0;i<data.length;i++){
      if(data[i].whiteCardCode===""||data[i].imeiCode===""){
        falseFlag=false;
      }
      let temp = data[i];
      for (let j = i + 1; j < data.length; j++)
      {
        if (temp.whiteCardCode===data[j].whiteCardCode)
        {
          repeatError = "白卡号" + temp.whiteCardCode + "有多条数据";
          falseFlag=false;
        }
        if (temp.imeiCode===data[j].imeiCode)
        {
          repeatError = repeatError+"   "+"IMEI" + temp.imeiCode + "有多条数据";
          falseFlag=false;
        }
      }
    }

    if(falseFlag){
      setBatchAddList(data);
      setExcelFlag(true);
    }
    else {
      message.error(repeatError);
      setExcelFlag(false);
    }
  }

  //递归修改item的key
  function disableSelect(arr: any[], ) {
    arr.map(item => {
      delete item.disabled
      item.key = item.deptID
      item.value = item.deptID
      if (typeof item.children === "undefined" || item.children === null || item.children.length === 0) {
        return;
      } else {
        item.selectable=false
        disableSelect(item.children)
      }
    })
  }
  const [form] = Form.useForm();

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 14 },
  };
  const dispatch = useDispatch()
  const tailLayout = {
    wrapperCol: { offset: 5, span: 14 },
  };

  function batchAddClick(){
    if(!excelFlag){
      message.error("excel数据异常，请修改！");
      return;
    }
    const param = {
      cardType:cardType,
      list:batchAddList
    };
    // console.log(param)
    addStudentCard.run(param);
  }

  function CardTypeOnChange(value:any) {
    setCardType(parseInt(value));
  }

  async function addStudentCardRequest(params: any)
  {
    console.log("批量新增")
    console.log(params)
    try {
      const json = await fetchRequest(url.ADD_STUDENT_CARD, params);
      if (json.success&&json.data.falseCount===0) {
        message.destroy();
        message.success("新增成功!");
        props.addSuccess();
      } else {
        if(json.data.falseCount!=0)
        {
          message.destroy();
          message.error("部分导入成功，导入成功"+json.data.successCount+"条，失败"+json.data.falseCount+"条！详情请看错误提示！！！");
          setErrorData(json.data.errorList);
        }
        else
        {
          message.destroy();
          message.error(json.data.error+"，详情请看错误提示！！！");
        }

      }
    } catch (error:any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const addStudentCard = useRequest(addStudentCardRequest, {
    manual: true,
    loadingDelay: 200
  })

  return (
      <div>
        <Content className="site-layout" style={{ padding: '0 50px', marginTop: 64 }}>
          <div className="site-layout-background" style={{  minHeight: 380 }}>
            <div style={{ display:"flex",flexDirection:"row",alignItems:"center",padding:20}}>
              <span>导入模板：</span>
              <a href={require('../../../excel/学生证批量入库模板.xlsx')} download>学生证批量入库模板</a>
            </div>
            <div style={{ display:"flex",flexDirection:"row",alignItems:"center",padding:20}}>
              <span>上传文件：</span>
              <input type="file" accept=".xlsx,.xls" onChange={handleExcelFile}/>
            </div>
            <div style={{ display:"flex",flexDirection:"row",alignItems:"center",padding:20}}>
              <span>学生卡类型：</span>
              <Select
                  style={{ width: '20%' }}
                  placeholder="请选择人员类型"
                  defaultValue="1"
                  onChange={CardTypeOnChange}
              >
                <Option value="1">智能学生证</Option>
                <Option value="2">普通白卡</Option>
              </Select>
            </div>
            <div style={{ padding:20 }}>
              <span>数据预览：</span>
              <Table style={{ marginTop:20 }}
                     pagination={{ hideOnSinglePage: true, simple: true,pageSize:10,total: excelTableData.length  }}
                     rowKey={(record: any) => record.rowNum} columns={columns} dataSource={excelTableData} />
            </div>
            <div  style={{ padding:20 }}>
              <Button type="primary" htmlType="submit" onClick={batchAddClick} loading={addStudentCard.loading}>提交</Button>
            </div>
            <div style={{ padding:20 }}>
              <span>错误提示：</span>
              <Table style={{ marginTop:20 }}
                     pagination={{ hideOnSinglePage: true, simple: true,pageSize:10,
                       total: errorData.length  }}
                     rowKey={(record: any) => record.rowNum} columns={errorcolumns}
                     dataSource={errorData} />
            </div>

          </div>
        </Content>
      </div>
  )

}
